package paper.parse;

import java.util.LinkedList;
import java.util.Iterator;
import paper.token.TT;

public class MatchBuilder {
    private LinkedList<MatchElement> list = new LinkedList<MatchElement>();
    MatchElement o = null;

    public void add(TT match, TT out) {
        if (o == null || match != o.match || out != o.out) {
            o = new MatchElement(match, out);
            list.add(o);
        } else {
            o.count++;
        }
    }

    public Iterator<MatchElement> iterator() {
        return list.iterator();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        TT old = TT.EOF;
        for (Iterator<MatchElement> i = list.iterator(); i.hasNext();) {
            MatchElement x = i.next();
            if (x.out != old) {
                sb.append(Character.toLowerCase(x.out.toChar()));
                old = x.out;
            }
            sb.append(x.toString());
        }
        return sb.toString();
    }
}
